home *** CD-ROM | disk | FTP | other *** search
- Path: oxy.rust.net!usenet
- From: ebennett@rust.net
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 1996 05:00:30 GMT
- Organization: Rust Net - High Speed Internet in Detroit 810-642-2276
- Message-ID: <4dpian$gij@oxy.rust.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: liv-12.rust.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
-
- >Is there a fast way to decide whether a number n is a power of 2?
-
-
- Working with positive numbers, a number will be a power of 2 if there
- is exactly one bit set in the number. (For negative numbers, you can
- use the following by taking the abs() of the number).
-
- Given some number, there is a neat trick to generate a mask which will
- have exactly one bit set in it. The bit set will be the least
- significant non-zero bit in the original number:
-
- mask = ~number & number;
-
- Now, if number contained a single non-zero bit (and is therefore a
- power of 2), mask will be equal to number. Therefore:
-
- if (number == (~number & number))
- {
- /* number is a power of 2 */
- }
-
- Try it, you'll like it!
-
- Earl
-
-
-